package br.ufrpe.bsi.pvs.xml.request;

import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;

import br.ufrpe.bsi.pvs.control.BSFactory;
import br.ufrpe.bsi.pvs.control.funcionario.FuncionarioBs;
import br.ufrpe.bsi.pvs.control.roupa.RoupaBs;
import br.ufrpe.bsi.pvs.model.funcionario.Funcionario;
import br.ufrpe.bsi.pvs.model.roupa.Estilo;
import br.ufrpe.bsi.pvs.model.roupa.Genero;
import br.ufrpe.bsi.pvs.model.roupa.Roupa;
import br.ufrpe.bsi.pvs.model.roupa.Tamanho;
import br.ufrpe.bsi.pvs.model.roupa.TipoCorporeo;
import br.ufrpe.bsi.pvs.model.roupa.TipoRoupa;
import br.ufrpe.bsi.pvs.xml.XMLUtil;
import br.ufrpe.bsi.pvs.xml.response.AddedResponseProcess;

/** process add requests */
public class AddRequestProcessor implements RequestProcessor {

	@Override
	public void process(Element request) {
		Element classe = request.getChild(XMLUtil.ELEM_CLASS);

		// if adding a employee (Funcionario)
		if (classe.getAttribute(XMLUtil.ATTR_NAME).getValue()
				.equals("funcionario")) {
			Funcionario f = new Funcionario();
			f.setNome(classe.getChildText("nome"));
			f.setLogin(classe.getChildText("login"));
			f.setSenha(classe.getChildText("senha"));

			FuncionarioBs bs = BSFactory.getFuncionarioBs();
			bs.salvar(f);

			XMLUtil.writeResponse(AddedResponseProcess
					.getAddedResponseDocument("funcionario"));
		}

		// if adding a cloth (Roupa)
		else {
			Roupa r = new Roupa();
			r.setDescricao(classe.getChildText("descricao"));
			r.setQuantEstoque(Integer.parseInt(classe
					.getChildText("quantEstoque")));

			r.setGenero(Genero.getGenero(Integer.parseInt(classe
					.getChildText("genero"))));

			r.setEstilo(Estilo.getEstilo(classe.getChildText("estilo")));

			r.setTipoRoupa(TipoRoupa.getTipoRoupa(classe
					.getChildText("tipoRoupa")));

			r.setTamanho(Tamanho.getTamanho(classe.getChildText("tamanho")));

			RoupaBs roupaBs = BSFactory.getRoupaBs();
			roupaBs.salvar(r);

			XMLUtil.writeResponse(AddedResponseProcess
					.getAddedResponseDocument("roupa"));
		}
	}

	/** generates a default add request xml document */
	public static Document getAddRequestDocument(String className) {
		Document document = new Document();

		Element root = new Element(XMLUtil.ELEM_ROOT);
		Element request = new Element(XMLUtil.ELEM_REQUEST);

		Attribute nomerequest = new Attribute(XMLUtil.ATTR_NAME, XMLUtil.ADD);
		request.setAttribute(nomerequest);
		root.addContent(request);

		Element classe = new Element(XMLUtil.ELEM_CLASS);
		Attribute nomeclasse = new Attribute(XMLUtil.ATTR_NAME, className);
		classe.setAttribute(nomeclasse);

		request.setContent(classe);
		document.setRootElement(root);

		return document;
	}

}
